package com.sy.simpleegg.platform

import android.content.Context
import android.net.wifi.WifiManager
import android.util.Log
import com.sy.simpleegg.R
import com.sy.simpleegg.app.App
import com.sy.simpleegg.bean.BackscanPayParamLyySdk
import com.sy.simpleegg.bean.BackscanPayParamWhmHex
import com.sy.simpleegg.bean.CashConfigBean
import com.sy.simpleegg.bean.DeviceConfig
import com.sy.simpleegg.bean.MotorConfigBean
import com.sy.simpleegg.bean.PayCodeParamLyySdk
import com.sy.simpleegg.bean.PayCodeParamWhmMqtt
import com.sy.simpleegg.bean.PayCodeParamWhmMqttHex
import com.sy.simpleegg.bean.RegDataBean
import com.sy.simpleegg.bean.RepCashKkb
import com.sy.simpleegg.bean.RepCashLyysdk
import com.sy.simpleegg.bean.RepCashWhmhex
import com.sy.simpleegg.bean.RepCashYch
import com.sy.simpleegg.bean.RepCoinDataBean
import com.sy.simpleegg.bean.RepCoinKkb
import com.sy.simpleegg.bean.RepCoinWhmhex
import com.sy.simpleegg.bean.RepCoinYch
import com.sy.simpleegg.bean.RepWriteOffKkb
import com.sy.simpleegg.bean.RepWriteOffWhm
import com.sy.simpleegg.bean.RepWriteOffYch
import com.sy.simpleegg.platform.lyysdk.bean.RecieveOrderLyySdkBean
import com.sy.simpleegg.bean.ReqBackscanPayBean
import com.sy.simpleegg.bean.ReqPayCodeBean
import com.sy.simpleegg.bean.ReqStartResultBean
import com.sy.simpleegg.bean.StartResultParamKkb
import com.sy.simpleegg.bean.StartResultParamLyyBox
import com.sy.simpleegg.bean.StartResultParamLyySdk
import com.sy.simpleegg.bean.StartResultParamWhmMqttHex
import com.sy.simpleegg.bean.StartResultParamYch
import com.sy.simpleegg.config.Config
import com.sy.simpleegg.constant.Constant
import com.sy.simpleegg.constant.Languages
import com.sy.simpleegg.constant.MultPlatform
import com.sy.simpleegg.ext.logFile
import com.sy.simpleegg.ext.showToastMsg
import com.sy.simpleegg.platform.defmqtt.bean.DefMqttParam
import com.sy.simpleegg.platform.kkb.KkbClient
import com.sy.simpleegg.platform.kkb.bean.KkbBuyPackageBean
import com.sy.simpleegg.platform.kkb.bean.KkbGoodBean
import com.sy.simpleegg.platform.kkb.bean.KkbSdkParam
import com.sy.simpleegg.platform.kkb.bean.RecieveOrderKkbBean
import com.sy.simpleegg.platform.kkb.bean.config.KkbGetPayCoinData
import com.sy.simpleegg.platform.kkb.bean.member.KkbQrCodeMemberInfoResponse
import com.sy.simpleegg.platform.kkb.bean.pay.KkbChannelWaitOffData
import com.sy.simpleegg.platform.kkb.bean.pay.RepCashDataBean
import com.sy.simpleegg.platform.lyybox.LyyBoxBusinessController
import com.sy.simpleegg.platform.lyybox.bean.LyyBoxParam
import com.sy.simpleegg.platform.lyybox.bean.RecieveOrderLyyBoxBean
import com.sy.simpleegg.platform.lyysdk.LyySdkClient
import com.sy.simpleegg.platform.lyysdk.ShowStyle
import com.sy.simpleegg.platform.lyysdk.bean.LyySdkGoodBean
import com.sy.simpleegg.platform.lyysdk.bean.LyySdkParam
import com.sy.simpleegg.platform.lyysdk.handler.LyyMsgHandler
import com.sy.simpleegg.platform.whm.MQConfig
import com.sy.simpleegg.platform.whm.WhmMqtt
import com.sy.simpleegg.platform.whm.bean.WhmGoodBean
import com.sy.simpleegg.platform.whm.bean.WhmMqttParam
import com.sy.simpleegg.platform.whm.cmd.CmdAssistant
import com.sy.simpleegg.platform.whm.cmd.CmdProducter
import com.sy.simpleegg.platform.whmhex.WhmMqttHex
import com.sy.simpleegg.platform.whmhex.bean.RecieveOrderWhmMqttHexBean
import com.sy.simpleegg.platform.whmhex.bean.RecieveWithdrawalCoinOrderWhmMqttHexBean
import com.sy.simpleegg.platform.whmhex.bean.WhmHexGoodBean
import com.sy.simpleegg.platform.whmhex.bean.WhmHexPayTypeBean
import com.sy.simpleegg.platform.whmhex.bean.WhmMqttHexParam
import com.sy.simpleegg.platform.whmhex.bean.WriteOffRespWhmMqttHexBean
import com.sy.simpleegg.platform.whmhex.config.WhmHexDevType
import com.sy.simpleegg.platform.ychsdk.YchClient
import com.sy.simpleegg.platform.ychsdk.bean.RecieveOrderYchBean
import com.sy.simpleegg.platform.ychsdk.bean.YchBuyPackageBean
import com.sy.simpleegg.platform.ychsdk.bean.YchGoodBean
import com.sy.simpleegg.platform.ychsdk.bean.YchSdkParam
import com.sy.simpleegg.platform.ychsdk.bean.config.GetPayCoinData
import com.sy.simpleegg.platform.ychsdk.bean.member.QrCodeMemberInfoResponse
import com.sy.simpleegg.platform.ychsdk.bean.pay.ChannelWaitOffData
import com.sy.simpleegg.upgrade.UpgradeUtil
import com.sy.simpleegg.util.BoardApiUtil
import com.sy.simpleegg.util.ByteUtil
import com.sy.simpleegg.util.CommonUtil
import com.sy.simpleegg.util.GsonUtil
import com.sy.simpleegg.util.MultiLanguageUtils
import com.sy.simpleegg.util.Preference
import com.sy.simpleegg.util.SPHelper
import com.sy.logger.Logger
import com.sy.mqhexsdk.bean.CashDataBean
import com.sy.mqhexsdk.bean.CoinsDataBean
import com.sy.mqhexsdk.bean.NetInfo
import com.sy.mqhexsdk.bean.SignalInfo
import com.sy.mqhexsdk.bean.rec.RecDownloadFile
import com.sy.mqhexsdk.bean.rec.RecUserInfoNew
import com.sy.mqhexsdk.util.HexUtil
import com.sy.simpleegg.util.WifiUtil
import com.sy.vendingmachine.platform.lyysdk.ShowType
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.util.Timer
import java.util.TimerTask

abstract class BaseManager(
    private val context: Context,
    private val defMqParam: DefMqttParam?,
    private val lyySdkParam: LyySdkParam?,
    private val lyyBoxParam: LyyBoxParam?,
    private val whmMqttParam: WhmMqttParam?,
    private val whmMqttHexParam: WhmMqttHexParam?,
    private val ychSdkParam: YchSdkParam?,
    private val kkbSdkParam: KkbSdkParam?,
) {
    private val TAG = javaClass.simpleName

    protected var coroutineScope: CoroutineScope? = null

    private var nettyJob: Job? = null

    //    private var defMqttClient: DefMqttClient? = null
    private var lyySdk: LyySdkClient? = null
    private var lyyBox: LyyBoxBusinessController? = null
    private var whmMqtt: WhmMqtt? = null
    private var whmMqttHex: WhmMqttHex? = null
    private var ychClient: YchClient? = null
    private var kkbClient: KkbClient? = null

    private var lyyBoxQrCodeJob: Job? = null
    private var hasLyyBoxQrCode = false

    private var upgradeJob: Job? = null
    private var upgradeVersion = ""
    private var upgradePkgTotalBlock = 0L
    private var upgradePkgBlockSort = 0L

    private var upgradeUtil: UpgradeUtil? = null

    private var whmUserInfo: RecUserInfoNew? = null

    private val regCodeMap: MutableMap<String, RegDataBean> = mutableMapOf()

    private var whmDeviceNumber = ""

    private var shopBindingCode = ""

    /**
     * 支付方式
     */
    private var payTypeStr: String by Preference(Constant.SETTING_PAY_TYPE, "")

    /**
     * 联系电话
     */
    private var contact: String by Preference(Constant.SETTING_CONTACT, "")

    /**
     * 国家地区
     */
    private var country: Int by Preference(Constant.SETTING_COUNTRY, Config.DEFAULT_COUNTRY_CODE)

    /**
     * 语言
     */
    private var language: Languages by Preference(Constant.SETTING_LANGUAGE_CONFIG, Languages.ZH)

    /**
     * 现金配置 lyy模板配置格式
     */
    private var cashConfigHex: String by Preference(Constant.SETTING_CASH_CONFIG, "0000000000000000000000000000000000000000")

    /**
     * 接入第三方平台
     */
    private var platform: BackstagePlatform by Preference(
        Constant.SETTING_OTHER_PLATFORM,
        BackstagePlatform.WHM_MQTT_HEX
    )

//    private var backstageCallback: OnBackstageCallback? = null

    init {

        coroutineScope = MainScope()

//        initMq()

//        openBackstage(backstageType)

        defMqParam?.let {
            regCodeMap[BackstagePlatform.DEF_MQTT.backstageName] = RegDataBean(context.resources.getString(R.string.regist_content))
            initMq(it)
        }

        lyySdkParam?.let {
            regCodeMap[BackstagePlatform.LYY_SDK.backstageName] = RegDataBean(context.resources.getString(R.string.regist_content_lyysdk))
            initLyyNetty(it)
        }

        lyyBoxParam?.let {
            initLyyBox(it)
        }

        whmMqttParam?.let {
            regCodeMap[BackstagePlatform.WHM_MQTT.backstageName] = RegDataBean(context.resources.getString(R.string.regist_content_whm_hex))
            initWhmMqtt(it)
        }

        whmMqttHexParam?.let {
            regCodeMap[BackstagePlatform.WHM_MQTT_HEX.backstageName] = RegDataBean(context.resources.getString(R.string.regist_content_whm_hex))
            initWhmMqttHex(it)
        }

        ychSdkParam?.let {
            regCodeMap[BackstagePlatform.YCH_SDK.backstageName] = RegDataBean(context.resources.getString(R.string.regist_content_ychsdk))
            initYchSdk(it)
        }

        kkbSdkParam?.let {
            regCodeMap[BackstagePlatform.KKB.backstageName] = RegDataBean(context.resources.getString(R.string.regist_content_kkb), status = 2)
            when (Config.OPEN_MULT_PLATFORM){
                MultPlatform.OPEN -> {
                    coroutineScope?.launch {
                        do {
                            delay(2000)
                        }while (whmDeviceNumber.isEmpty())
                        it.mainBoardNum = whmDeviceNumber
                        initKkbSdk(it)
                    }
                }
                MultPlatform.CLOSE -> initKkbSdk(it)
            }
        }
    }

    fun release() {
        coroutineScope?.cancel()
    }

    private fun initMq(param: DefMqttParam) {
        try {
//            mqttManager = MqttManager(devNumber, devTypeMq, ver, context)
//            mqttManager?.setCallback(object : MqttManager.OnMqttDataCallback {
//                override fun toLogin() {
//                    log("mqtt默认平台主题订阅成功，需要执行登录指令")
//                    //订阅主题成功，需要MainActivity开启处理订单线程
//                    backstageCallback?.toLogin()
//                }
//
//                override fun connectionChange(connectState: Boolean) {
//                    log("mqtt默认平台链接状态改变：${if (connectState) "链接成功" else "断开链接"}")
//                    backstageCallback?.onConnectionChange(BackstagePlatform.DEFAULT_MQTT, connectState)
//                }
//
//                override fun reLogin() {
//                    log("mqtt默认平台登录失败，重新执行登录指令")
//                    publishLogin()
//                }
//
//                override fun onLoginSuccess() {
//                    log("mqtt默认平台登录指令成功")
//                    backstageCallback?.onLoginSuccess(BackstagePlatform.DEFAULT_MQTT, null)
//
//                    //上报iccid
//                    devInit()
//                    //开启心跳
//                    startHeartBeat()
//                    //获取套餐数据
//                    publishGetPackage(0, MQConfig.PACKAGE_TYPE_NORMAL)
//                }
//
//                override fun getPackage(pkgCount: Int, pkgType: Int) {
//                    log("mqtt默认平台套餐数据，数量：$pkgCount 类型：$pkgType")
//                    backstageCallback?.onGetPackage(BackstagePlatform.DEFAULT_MQTT, pkgCount, pkgType)
//                }
//
//                override fun refreshPackageData() {
//                    log("mqtt默认平台刷新套餐数据")
//                    backstageCallback?.onRefreshPackageData(BackstagePlatform.DEFAULT_MQTT)
//                }
//
//                override fun onBillResponse(success: Boolean, billMsgNumber: String) {
//                    log("mqtt默认平台投钞数据响应")
//                    backstageCallback?.onBillResp(BackstagePlatform.DEFAULT_MQTT, success, billMsgNumber)
//                }
//
//                override fun receiveOrder(orderEntity: OrderEntity, msg: String?) {
//                    log("mqtt默认平台收到订单：${GsonUtil.getInstance().toJson(orderEntity)}")
//                    backstageCallback?.onReceiveOrder(BackstagePlatform.DEFAULT_MQTT, orderEntity, msg)
//                }
//
//                override fun showPayCode(payCodeData: String, type: Int) {
//                    log("mqtt默认平台显示二维码：$payCodeData ${if (type == 1) "二维码" else "图片"}")
//                    backstageCallback?.onShowPayCode(BackstagePlatform.DEFAULT_MQTT, payCodeData, type)
//                }
//
//                override fun responseTips() {
//                    log("mqtt默认平台响应后台收到提示")
//                }
//
//                override fun showTips(color: Int, tips: String) {
//                    log("mqtt默认平台显示提示信息：$tips 颜色：${if (color == 1) "黑色" else "红色"}")
//                    backstageCallback?.onShowTips(BackstagePlatform.DEFAULT_MQTT, color, tips)
//                }
//
//            })
        } catch (e: Exception) {
            e.printStackTrace()
            log("initMq()异常：${e.message}")
        }
    }

    /**
     * lyy SDK通讯
     */
    private fun initLyyNetty(param: LyySdkParam) {
        try {
            param.run {
                val msgHandler = LyyMsgHandler(object : LyyMsgHandler.OnNettyCallback {
                    override fun onLoginSuccess(devNumber: String?) {
                        logFile("onLoginSuccess devNumber=$devNumber")
                        refreshRegCode(BackstagePlatform.LYY_SDK, "", 2)
                        onLoginSuccess(BackstagePlatform.LYY_SDK, devNumber)
                        lyySdk?.getRule()
                    }

                    override fun showRegist(show: ShowType, registCode: String?) {
                        logFile("showRegist show=$show registCode=$registCode")
                        val isShow = when (show) {
                            ShowType.SHOW -> {
                                //未绑定
                                refreshRegCode(BackstagePlatform.LYY_SDK, registCode?:"", 1)
                                true
                            }
                            ShowType.HIDE -> {
                                //绑定
                                refreshRegCode(BackstagePlatform.LYY_SDK, registCode?:"", 2)
                                false
                            }
                            ShowType.OTHER -> {
                                //解绑
                                refreshRegCode(BackstagePlatform.LYY_SDK, registCode?:"", 1)
                                false
                            }
                        }
//                        onShowRegist(BackstagePlatform.LYY_SDK, isShow, registCode)
                    }

                    override fun showPayCode(payCodeData: String?, showType: ShowStyle) {
                        logFile("showPayCode payCodeData=$payCodeData showType=$showType")
                        onShowPayCode(BackstagePlatform.LYY_SDK, payCodeData, 0)
                    }

                    override fun receiveOrder(
                        money: String,
                        coins: String,
                        k: String,
                        unique: String
                    ) {
                        logFile("receiveOrder k=$k")
                        val orderBean = RecieveOrderLyySdkBean(money, coins, k, unique)
                        onReceiveOrder(BackstagePlatform.LYY_SDK, orderBean)
                    }

                    override fun refreshPackageData(dataList: MutableList<LyySdkGoodBean>) {
                        logFile("refreshPackageData")
                        onRefreshPackageData(BackstagePlatform.LYY_SDK, dataList)
                    }

                })
//            msgHandler.setPayResultVerify {
//                verifyOrder(it)
//            }

//            lyySdk = LyySdkClient(
//                "7b9d7bd26e7cea16",// 1c78874465a4ec86
//                "e867c7d30fb23da04c5dbf583ec128c4",// 33f993659af53d02226e279c39002d94
//                "ehw.leyaoyao.com",
//                5923,
////                BoardApiUtil.getDeviceId(),
//                "dbjf4efef9a9b666290",
//                "DBJ",
//                "5663",// 5850
//                msgHandler
//            )
                lyySdk = LyySdkClient(
                    appid,
                    appSecret,
                    host,
                    port,
                    uuid,
                    devType,
                    loginFlag,
                    msgHandler
                )
                lyySdk?.connect()
            }
        } catch (e: Exception) {
            e.printStackTrace()
            logFile("打开lyysdk通讯异常：${e.message}")
        }

//        nettyJob?.cancel()
//
//        nettyJob = coroutineScope?.launch(Dispatchers.IO) {
//
//            val msgHandler = LyyMsgHandler(object : LyyMsgHandler.OnNettyCallback {
//                override fun onLoginSuccess(devNumber: String?) {
//                    logFile("onLoginSuccess devNumber=$devNumber")
//                    onLoginSuccess(BackstagePlatform.LYY_SDK, devNumber)
//                    lyySdk?.getRule()
//                }
//
//                override fun showRegist(show: ShowType, registCode: String?) {
//                    logFile("showRegist show=$show registCode=$registCode")
//                    val isShow = when (show) {
//                        ShowType.SHOW -> true
//                        ShowType.HIDE -> false
//                        ShowType.OTHER -> false
//                    }
//                    onShowRegist(BackstagePlatform.LYY_SDK, isShow, registCode)
//                }
//
//                override fun showPayCode(payCodeData: String?, showType: ShowStyle) {
//                    logFile("showPayCode payCodeData=$payCodeData showType=$showType")
//                    onShowPayCode(BackstagePlatform.LYY_SDK, payCodeData, 0)
//                }
//
//                override fun receiveOrder(money: String, coins: String, k: String, unique: String) {
//                    logFile("receiveOrder k=$k")
//                    val orderBean = RecieveOrderLyySdkBean(money, coins, k, unique)
//                    onReceiveOrder(BackstagePlatform.LYY_SDK, orderBean)
//                }
//
//                override fun refreshPackageData(dataList: MutableList<LyySdkGoodBean>) {
//                    logFile("refreshPackageData")
//                    onRefreshPackageData(BackstagePlatform.LYY_SDK, dataList)
//                }
//
//            })
////            msgHandler.setPayResultVerify {
////                verifyOrder(it)
////            }
//            lyySdk = LyySdkClient(
//                "7b9d7bd26e7cea16",// 1c78874465a4ec86
//                "e867c7d30fb23da04c5dbf583ec128c4",// 33f993659af53d02226e279c39002d94
//                "ehw.leyaoyao.com",
//                5923,
////                BoardApiUtil.getDeviceId(),
//                "dbjf4efef9a9b666290",
//                "DBJ",
//                "5663",// 5850
//                msgHandler
//            )
//            lyySdk?.connect()
//        }

    }

    /**
     * 乐摇摇盒子通讯
     */
    private fun initLyyBox(param: LyyBoxParam) {
        param.run {
            lyyBox = LyyBoxBusinessController(
                did,
                "/dev/$portName",
                baudrate,
                stopb,
                datab,
                parity,
                loginFlag,
                200
            )
            lyyBox?.setOnDataReceivedListener(object :
                LyyBoxBusinessController.OnDataReceivedListener {
                override fun onPushCheckConnect(dataHex: String) {
                    val uniqueCodeHex = dataHex.substring(10, 22)
                    lyyCheckBoardConnecton(BackstagePlatform.LYY_BOX, dataHex, uniqueCodeHex)
                }

                override fun onPushCloud(addCodeHex: String, coinsHex: String, amountHex: String) {
                    //AA080103 A1 0100 0100 ABDD
                    log("控制板暂无处理：云上分")
                    val uniqueCode = CommonUtil.unRepeatSixCode() + addCodeHex
                    val coinsTemp = coinsHex.substring(2) + coinsHex.substring(0, 2)
                    val amountTemp = amountHex.substring(2) + amountHex.substring(0, 2)
                    val order = RecieveOrderLyyBoxBean(
                        ByteUtil.hexStr2decimal(amountTemp).toString(),
                        ByteUtil.hexStr2decimal(coinsTemp).toString(),
                        uniqueCode
                    )
                    onReceiveOrder(BackstagePlatform.LYY_BOX, order)
                }

                override fun onPushCheckState(dataHex: String) {
                    val uniqueCodeHex = dataHex.substring(10, 22)
                    lyyGetBoardState(BackstagePlatform.LYY_BOX, dataHex, uniqueCodeHex)
                }

//                override fun onPushCloudNew(orderEntity: OrderEntity, dataHex: String) {
//                    BackstagePlatform.LYY_BOX,
//                    onReceiveOrder(BackstagePlatform.LYY_BOX, orderEntity, "")
//                }

                override fun onPushCloudNew(
                    uniqueCodeHex: String,
                    amountHex: String,
                    coinsHex: String,
                    dataHex: String
                ) {
                    val order = RecieveOrderLyyBoxBean(
                        ByteUtil.hexStr2decimal(amountHex).toString(),
                        ByteUtil.hexStr2decimal(coinsHex).toString(),
                        ByteUtil.hexStr2decimal(uniqueCodeHex).toString()
                    )
                    onReceiveOrder(BackstagePlatform.LYY_BOX, order)
                }

                override fun onPushOutResultResp(dataHex: String) {
                    lyyRespLyyBoardOutResult(BackstagePlatform.LYY_BOX, dataHex)
                }

                override fun onPushGetTerminalConfig(dataHex: String) {
                    lyyGetBoardConfig(BackstagePlatform.LYY_BOX, dataHex)
                }

                override fun onPushSetTerminalConfig(dataHex: String) {
                    lyySetBoardConfig(BackstagePlatform.LYY_BOX, dataHex)
                }

                override fun onPushPayQrCodeResp(dataHex: String) {
                    hasLyyBoxQrCode = true
                    val cmdLen = dataHex.length
                    val codeDataHex = dataHex.substring(8, cmdLen - 4)
//                backstageCallback?.lyyToShowPayQrCode(codeDataHex)
                    val qrCode = ByteUtil.hexStringToString(codeDataHex)
                    onShowPayCode(BackstagePlatform.LYY_BOX, qrCode, 0)
                }

                override fun onPushOutCountListResp(dataHex: String) {
                    lyyRespListAdd(BackstagePlatform.LYY_BOX, dataHex)
                }

                override fun onPushNetworkResp(dataHex: String) {
                    lyyRespBoxNetwork(BackstagePlatform.LYY_BOX, dataHex)
                }

                override fun onHeartBeat(heartBeat: Boolean) {
                    lyyRespBoxHeartBeat(BackstagePlatform.LYY_BOX, heartBeat)
                }

            })
//            lyyBox?.getBoxNetwork()
            getLyyBoxQrCode()
        }
    }

    private fun initWhmMqtt(param: WhmMqttParam) {
        try {
            param.run {
                whmMqtt = WhmMqtt(devNumber, devTypeMq, protolVer, context).apply {
                    setCallback(object : WhmMqtt.OnMqttDataCallback {
                        override fun toLogin() {
                            log("mqtt默认平台主题订阅成功，需要执行登录指令")
                            //订阅主题成功，需要MainActivity开启处理订单线程
//                            toLogin()
                        }

                        override fun connectionChange(connectState: Boolean) {
                            log("mqtt默认平台链接状态改变：${if (connectState) "链接成功" else "断开链接"}")
                            onConnectionChange(BackstagePlatform.WHM_MQTT, connectState)
                        }

                        override fun reLogin() {
                            log("mqtt默认平台登录失败，重新执行登录指令")
                            publishLogin()
                        }

                        override fun onLoginSuccess() {
                            log("mqtt默认平台登录指令成功")
                            onLoginSuccess(BackstagePlatform.WHM_MQTT, null)

                            //上报iccid
                            devInit()
                            //开启心跳
                            startHeartBeat()
                            //获取套餐数据
                            publishGetPackage(0, MQConfig.PACKAGE_TYPE_NORMAL)
                        }

                        override fun getPackage(pkgCount: Int, pkgType: Int) {
                            log("mqtt默认平台套餐数据，数量：$pkgCount 类型：$pkgType")
                            onGetPackage(BackstagePlatform.WHM_MQTT, pkgCount, pkgType)
                        }

                        override fun refreshPackageData(dataList: MutableList<WhmGoodBean>) {
                            log("mqtt默认平台刷新套餐数据")
                            onRefreshPackageData(BackstagePlatform.WHM_MQTT, dataList)
                        }

                        override fun onBillResponse(success: Boolean, billMsgNumber: String) {
                            log("mqtt默认平台投钞数据响应")
                            onBillResp(BackstagePlatform.WHM_MQTT, success, billMsgNumber)
                        }

                        override fun receiveOrder(
                            money: String,
                            coins: String,
                            k: String,
                            type: Int,
                            accountMoney: String,
                            accountCoins: String
                        ) {
//                            log("mqtt默认平台收到订单：${GsonUtil.getInstance()!!.toJson(orderEntity)}")
//                            val orderBean = RecieveOrderWhmBean(money, coins, k, type, accountMoney, accountCoins)
//                            onReceiveOrder(BackstagePlatform.WHM_MQTT, orderEntity, msg)
                        }

                        override fun showPayCode(payCodeData: String, type: Int) {
                            log("mqtt默认平台显示二维码：$payCodeData ${if (type == 1) "二维码" else "图片"}")
                            onShowPayCode(BackstagePlatform.WHM_MQTT, payCodeData, type)
                        }

                        override fun responseTips() {
                            log("mqtt默认平台响应后台收到提示")
                        }

                        override fun showTips(color: Int, tips: String) {
                            log("mqtt默认平台显示提示信息：$tips 颜色：${if (color == 1) "黑色" else "红色"}")
                            onShowTips(BackstagePlatform.WHM_MQTT, color, tips)
                        }

                    })
                }

            }
        } catch (e: Exception) {
            e.printStackTrace()
            log("initMq()异常：${e.message}")
        }
    }

    private fun initWhmMqttHex(param: WhmMqttHexParam) {
        try {
            param.run {
                whmMqttHex = WhmMqttHex(
                    context,
                    -1,//非售货机
                    protocalVersion,
                    clientId,
                    hardwareCode,
                    userName,
                    password,
                    host,
                    authHost,
                    platformCode,
                    commonKey,
                    privateKey,
                    {
                        val netType = when (Constant.NETWORK_TYPE) {
                            "WIFI" -> 2
                            else -> 1
                        }
                        val iccidOrSsid = when (netType) {
                            1 -> BoardApiUtil.getIccid() ?: ""
                            else -> {
                                val wifiManager =
                                    App.instance.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
                                wifiManager.connectionInfo.ssid
                            }
                        }
                        logFile("登录方式：${if (netType == 2) "WIFI" else "4G"} ssidOrIccid:$iccidOrSsid")
                        NetInfo(netType, iccidOrSsid)
                    },
                    {
                        val signal = Constant.NETWORK_SIGNAL
                        val signalValue = when {
                            signal < 0 -> 0
                            signal in 0..100 -> signal
                            else -> 100
                        }
                        SignalInfo(1, signalValue)
                    },
                    when (SPHelper.getGoodType()){
                        3 -> WhmHexDevType.UNIT_TYPE_COIN
                        4 -> WhmHexDevType.UNIT_TYPE_BEAD
                        else -> WhmHexDevType.UNIT_TYPE_COIN
                    }
                ).apply {
                    setCallback(object : WhmMqttHex.OnMqttDataCallback {
                        override fun onShowRegistCode(cpuId: String) {
                            refreshRegCode(BackstagePlatform.WHM_MQTT_HEX, cpuId, 1)
//                            onShowRegist(BackstagePlatform.WHM_MQTT_HEX, true, cpuId)
                        }

                        override fun onLoginSuccess(devNumber: String, qrCode: String) {
                            refreshRegCode(BackstagePlatform.WHM_MQTT_HEX, devNumber, 2)
                            whmDeviceNumber = devNumber
                            shopBindingCode = qrCode
                            onLoginSuccess(BackstagePlatform.WHM_MQTT_HEX, devNumber)
                            //查询APP版本
                            repCheckAppVer(clientId)
                            when (Config.OPEN_MULT_PLATFORM){
                                MultPlatform.OPEN -> {
                                    if (platform != BackstagePlatform.WHM_MQTT_HEX) return
                                }
                                MultPlatform.CLOSE -> {

                                }
                            }
                            //获取门店信息
                            getShopInfo()
                        }

                        override fun refreshPackageData(dataList: MutableList<WhmHexGoodBean>) {
                            logFile("套餐数据")
                            onRefreshPackageData(BackstagePlatform.WHM_MQTT_HEX, dataList)
                        }

                        override fun onBillResponse(sucess: Boolean, billMsgNumber: String) {

                        }

                        override fun receiveOrder(
                            sn: String,
                            value: Long,
                            unit: Int,
                            payType: Int,
                            amount: String,
                            accountRemainAmount: String,
                            payMoneyUnit: Int
                        ) {
                            onReceiveOrder(
                                BackstagePlatform.WHM_MQTT_HEX, RecieveOrderWhmMqttHexBean(
                                    amount,
                                    value.toString(),
                                    sn,
                                    sn,
                                    false,
                                    payType,
                                    unit,
                                    accountRemainAmount,
                                    payMoneyUnit
                                )
                            )
                        }

                        override fun responseTips() {

                        }

                        override fun showTips(color: Int, tips: String) {

                        }

                        override fun onFuncListInfo(
                            updateTime: String,
                            totalSum: Int,
                            startSort: Int,
                            sum: Int,
                            infos: MutableList<String>,
                            descHex: String
                        ) {

                        }

                        override fun onUploadFuncResult(sum: Int, state: String) {

                        }

                        override fun onHeartBeat(
                            stateHex: String,
                            success: Boolean,
                            descHex: String
                        ) {

                        }

                        override fun onRecTime(time: String, timeZone: String) {

                        }

                        override fun onShopInfo(phoneNumber: String?, shopName: String?) {
                            if (phoneNumber == null && shopName == null && shopBindingCode.isNotEmpty()){
                                //设备未绑定门店，需要显示二维码
                                refreshRegCode(BackstagePlatform.WHM_MQTT_HEX, shopBindingCode, 1)
                                coroutineScope?.launch {
                                    delay(5000)
                                    getShopInfo()
                                }
                            }else{
                                refreshRegCode(BackstagePlatform.WHM_MQTT_HEX, shopBindingCode, 2)
                                //设备已绑定门店
                                contact = phoneNumber?:""
                                //获取支付方式
                                getPayTypeList(0, 0, 0)
                                //获取套餐数据
                                getPackages()
                                //获取消费者登录二维码
//                            getLoginCode()
                                //获取提币二维码
//                            getWithdrawalCode()
                            }
                        }

                        override fun onDeviceStateResp(stateHex: String, descHex: String) {

                        }

                        override fun onPackageById(
                            pkgType: Int,
                            pkgList: MutableList<WhmHexGoodBean>
                        ) {

                        }

                        override fun onPackagesUpdate(
                            pkgType: Int,
                            totalSum: Int,
                            updateIdHexList: MutableList<String>
                        ) {

                        }

                        override fun onPayTypeList(
                            totalSum: Int,
                            startSort: Int,
                            sum: Int,
                            payTypeList: MutableList<WhmHexPayTypeBean>
                        ) {
                            var result = ""
                            payTypeList.forEach { payType ->
                                result += "${payType.id},${payType.name};"
                            }
                            payTypeStr = result
                        }

                        override fun onPayCode(sn: String, codeData: String) {
                            onShowPayCode(BackstagePlatform.WHM_MQTT_HEX, "$sn,$codeData", 0)
                        }

                        override fun onCodePayResult(sn: String, payResult: Int) {
                            logFile("二维码支付结果：sn=$sn payResult=$payResult")
                        }

                        override fun onDeviceErrStateResp(
                            type: Int,
                            lv: Int,
                            errCode: String,
                            state: String
                        ) {

                        }

                        override fun onReverseData(dataLen: Long) {

                        }

                        override fun onSaveCoinResp(result: Boolean) {
                            onSaveCoinResult(BackstagePlatform.WHM_MQTT_HEX, result)
                        }

                        override fun onVerifyDataResp(dataLen: Long, result: Boolean, errMsg: String) {
                            onWriteOffResult(BackstagePlatform.WHM_MQTT_HEX, WriteOffRespWhmMqttHexBean(dataLen, result, errMsg))
                        }

                        override fun onSwipeCardDataResp(dataLen: Long) {

                        }

                        override fun onUpgradeBlock(
                            totalBlock: Long,
                            blockSort: Long,
                            blockDataHex: String
                        ) {
                            if (totalBlock > 0 && blockSort == 0L) {
                                upgradePkgTotalBlock = totalBlock
                                upgradePkgBlockSort = 1
                                upgradeUtil = UpgradeUtil(
                                    upgradeVersion,
                                    Config.DEF_UPGRADE_PATH,
                                    upgradePkgTotalBlock
                                )
                                repUpgradeBlock(
                                    upgradeVersion,
                                    upgradePkgTotalBlock,
                                    upgradePkgBlockSort
                                )
                            } else if (totalBlock > 0 && blockSort > 0L) {
                                upgradeJob = coroutineScope?.launch(Dispatchers.IO) {
                                    HexUtil.hexToByteArray(blockDataHex)?.let {
                                        upgradeUtil?.saveBlock(it, blockSort)
                                        if (upgradePkgTotalBlock == blockSort) {
                                            upgradeUtil?.mergeBlocks()?.let {
                                                if (it.isNotEmpty()) {
                                                    BoardApiUtil.installSilence(it)
                                                }
                                            }
                                        }
                                        upgradePkgBlockSort++
                                        repUpgradeBlock(
                                            upgradeVersion,
                                            upgradePkgTotalBlock,
                                            upgradePkgBlockSort
                                        )
                                    }
                                }

                            } else {
                                logFile("更新包数据异常：totalBlock=$totalBlock blockSort=$blockSort")
                            }
                        }

                        override fun onForceUpgrade(upgradeVer: String) {
                            upgradeVersion = upgradeVer
                            repUpgradeBlock(upgradeVer, 0, 0)
                        }

                        override fun onCashDataResp(result: Int, successPkgSum: Int) {

                        }

                        override fun onReboot(msg: String) {
                            logFile("重启设备")
                            BoardApiUtil.rebootSystem()
                        }

                        override fun onWifi(ssid: String, pwd: String) {
                            setWifi(ssid, pwd)
                        }

                        override fun onCheckOrder(sn: String) {

                        }

                        override fun onTransmission(dataLen: Long, dataHex: String) {
//                            parseTransmissionData(dataHex)
                        }

                        override fun onTransmissionResp(accessDataByteSum: Long) {

                        }

                        override fun onCmdNumberData(
                            cmdNumber: String,
                            dataLen: Long,
                            dataHex: String
                        ) {
                            logFile("透传编号：$cmdNumber")
                            parseTransmissionData(cmdNumber, dataHex)
                        }

                        override fun onCmdNumberDataResp(
                            cmdNumber: String,
                            accessDataByteSum: Long
                        ) {

                        }

                        override fun onGoodSingle(
                            goodId: String,
                            goodPrice: String,
                            priceUnit: Int,
                            stock: Long,
                            update: String
                        ) {

                        }

                        override fun onGoodStockResp(
                            result: Int,
                            updateType: Int,
                            afterStock: Long,
                            update: String
                        ) {

                        }

                        override fun onMqttOpen() {
                            val netType = when (Constant.NETWORK_TYPE) {
                                "WIFI" -> 2
                                else -> 1
                            }
                            val iccidOrSsid = when (netType) {
                                1 -> BoardApiUtil.getIccid() ?: ""
                                else -> {
                                    val wifiManager =
                                        App.instance.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
                                    wifiManager.connectionInfo.ssid
                                }
                            }
                            logFile("登录方式：${if (netType == 2) "WIFI" else "4G"} ssidOrIccid:$iccidOrSsid")
                            val appVer = BoardApiUtil.getVersionName(App.instance)?:"undefine"
                            whmMqttHex?.login(
                                netType,
                                appVer,
                                iccidOrSsid,
                                "1.0",
                                "1.0",
                                "00"
                            )
                        }

                        override fun onUserLogin(recUserInfoNew: RecUserInfoNew) {
                            whmUserInfo = recUserInfoNew
                            onUserLoginDev(recUserInfoNew)
                        }

                        override fun onDownloadFile(recDownloadFile: RecDownloadFile) {

                        }

                        override fun onDevLoginQrCode(code: String) {
                            onShowLoginCode(code)
                        }

                        override fun onDevConsumeCode(code: String) {
                            onRecDevConsumeCode(code)
                        }

                        override fun onDevLogout() {
                            whmUserInfo = null
                            onDevLogoutResp()
                        }

                        override fun onWithdrawalCode(code: String) {
                            onShowWithdrawalCode(code)
                        }

                        override fun onWithdrawalOrder(
                            orderNumber: String,
                            withdrawalCoins: Long,
                            accountCoins: Long,
                            measurementUnit: Int,
                        ) {
                            onReceiveWithdrawalCoinOrder(
                                BackstagePlatform.WHM_MQTT_HEX, RecieveWithdrawalCoinOrderWhmMqttHexBean(
                                    "",
                                    withdrawalCoins.toString(),
                                    orderNumber,
                                    orderNumber,
                                    false,
                                    -1,
                                    measurementUnit,
                                    "",
                                    -1,
                                    accountCoins
                                )
                            )
                        }

                        override fun onWithdrawalOrderNew(
                            userId: String,
                            walletType: Int,
                            orderNumber: String,
                            amount: String,
                            amountUnit: Int,
                            balance: String,
                        ) {
                            onReceiveWithdrawalCoinOrder(
                                BackstagePlatform.WHM_MQTT_HEX, RecieveWithdrawalCoinOrderWhmMqttHexBean(
                                    "",
                                    amount,
                                    orderNumber,
                                    orderNumber,
                                    false,
                                    -1,
                                    amountUnit,
                                    balance,
                                    -1,
                                    balance.toLong(),
                                    walletType
                                )
                            )
                        }

                        override fun onUpgradeApp(fileId: String, name: String, url: String) {
                            onUpgrade(fileId, name, url)
                        }

                        override fun onRecLogCommand(logType: Int, logNumber: String) {
                            onUploadLog(logType, logNumber)
                        }
                    })
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
            log("initMqttHex()异常：${e.message}")
        }
    }

    /**
     * 初始化油菜花通讯
     */
    private fun initYchSdk(param: YchSdkParam){
        try {
            param.run {
                ychClient = YchClient(
                    ssid, mainBoardNum, agreement, agreementVer, devType, title, appSoftVer, netIp, netMask, netGateWay,
                    object : YchClient.YchClientListener{
                        override fun registerFailed(errorCode: Long, errorMsg: String?) {

                        }

                        override fun needUpdate(vararg updateAddress: String?) {

                        }

                        override fun bindStatus(isSuccess: Boolean, deviceNumber: String?) {
                            deviceNumber?.let {
                                refreshRegCode(BackstagePlatform.YCH_SDK, it, if (isSuccess) 2 else 1)
                            }

                            if (isSuccess) {
                                refreshRegCode(BackstagePlatform.YCH_SDK, deviceNumber?:"", 2)
                                onLoginSuccess(BackstagePlatform.YCH_SDK, deviceNumber)
                            }
//                            else{
//                                onShowRegist(BackstagePlatform.YCH_SDK, true, deviceNumber)
//                            }
                        }

                        override fun onError(type: String?, errorCode: Long, msg: String?) {

                        }

                        override fun deviceBinding(devNumber: String) {
                            showToastMsg(context.getString(R.string.binding_and_reboot_tips))
                            val timer = Timer()
                            timer.schedule(object : TimerTask(){
                                override fun run() {
                                    BoardApiUtil.rebootSystem()
                                }
                            }, 3000)
                        }

                        override fun deviceUnBinding() {

                        }

                        override fun deviceReBoot() {
                            BoardApiUtil.rebootSystem()
                        }

                        override fun extractCoin(isMqOrder: Boolean, coins: String, money: String, orderId: String) {
                            if (money == "0"){
                                onReceiveWithdrawalCoinOrder(BackstagePlatform.YCH_SDK, RecieveOrderYchBean(
                                    orderId,//事务id
                                    money,
                                    coins,
                                    orderId,//订单id
                                    orderId,//订单号
                                    false,
                                    isMqOrder
                                ))
                            }else{
                                onReceiveOrder(BackstagePlatform.YCH_SDK, RecieveOrderYchBean(
                                    orderId,//事务id
                                    money,
                                    coins,
                                    orderId,//订单id
                                    orderId,//订单号
                                    false,
                                    isMqOrder
                                ))
                            }
                        }

                        override fun getDeviceSetting(dataJson: String?) {

                        }

                        override fun setDeviceSetting(dataJson: String?) {

                        }

                        override fun changeCashPackage() {

                        }

                        override fun updateOrder(
                            orderId: String?,
                            transactionId: String?,
                            deviceStatus: Int,
                            remark: String?,
                        ) {

                        }

                        override fun deviceStatues(status: Int) {

                        }

                        override fun loginComplete() {
                            ychClient?.getCoinPackage(1)//1-普通套餐 2-充值套餐 3-所有套餐
                            ychClient?.getConfig()
                        }

                        override fun updateCoinsPackage(coinsPackage: MutableList<YchGoodBean>) {
                            onRefreshPackageData(BackstagePlatform.YCH_SDK, coinsPackage)
                        }

                        override fun updateConfig(configData: GetPayCoinData) {
                            //1元x币配置
                            logFile("YCH 1元x币配置 ${GsonUtil.getInstance()?.toJson(configData)}")
                            val defaultCoins = configData.Coins.toString()
                            if (defaultCoins.isNotEmpty()) {
                                val defaultMoneyCoins = Config.DEFAULT_MONEY_COINS.split(",")
                                val dMoney = defaultMoneyCoins[0]
                                val dCoins = defaultMoneyCoins[1]
                                Config.DEFAULT_MONEY_COINS = "100,$dCoins"
                            }

                            var cashConfig = ""
                            val banknoteChannelConfigs = CommonUtil.getChannelMode(country).split(";")[0].split(",")

                            banknoteChannelConfigs.forEachIndexed { index, channelCashStr ->
                                val channelCash = channelCashStr.toLong()
                                if (channelCash <= 0L){
                                    cashConfig = "$cashConfig${"0000"}"
                                    return@forEachIndexed
                                }

                                configData.CashList.forEach { cash ->
                                    if (cash.Money*100L == channelCash){
                                        val coinsHex = ByteUtil.int2HexStr(cash.Coins, 4, true)
                                        cashConfig = "$cashConfig$coinsHex"
                                        return@forEachIndexed
                                    }
                                }
                                cashConfig = "$cashConfig${"0000"}"
                            }
                            logFile("YCH 纸钞出币配置 $cashConfig")
                            cashConfigHex = cashConfig
                        }

                        override fun showPayCode(
                            transId: String,
                            orderId: String,
                            orderNumber: String,
                            codeData: String,
                        ) {
                            onShowPayCode(BackstagePlatform.YCH_SDK, "$transId,$orderId,$orderNumber,$codeData", 0)
                        }

                        override fun onPlaceOrder(
                            transId: String,
                            orderId: String,
                            orderNumber: String,
                            goodId: String,
                            coins: String,
                            money: String
                        ) {
                            placeOrder(BackstagePlatform.YCH_SDK, transId, orderId, orderNumber, goodId, coins, money)
                        }

                        override fun placeOrderResult(transId: String, paySuccess: Boolean) {
                            onReceiveOrderYchHttp(BackstagePlatform.YCH_SDK, RecieveOrderYchBean(
                                transId,//事务id
                                "",
                                "",
                                transId,//订单id
                                "",//订单号
                                false,
                                false
                            ),
                                paySuccess)
                        }

                        override fun showBuyConsumptionCode(codeData: String) {
                            onShowPayCode(BackstagePlatform.YCH_SDK, codeData, 0)
                        }

                        override fun showDevConsumptionCode(codeData: String) {
                            onRecDevConsumeCode(codeData)
                        }

                        override fun getLoginCode(codeData: String, transId: String) {
                            onShowLoginCode("$codeData,$transId")
                        }

                        override fun onLgLogin(loginMemberInfo: QrCodeMemberInfoResponse) {
                            onUserLoginDevYch(loginMemberInfo)
                        }

                        override fun saveCoinsFinish(balance: Long) {
                            onSaveCoinResult(BackstagePlatform.YCH_SDK, true)
                        }

                        override fun writeOffResult(writeOffResult: ChannelWaitOffData) {
                            onReceiveWriteOffOrder(BackstagePlatform.YCH_SDK, RecieveOrderYchBean(
                                writeOffResult.OrderID,
                                "0",
                                writeOffResult.Coin.toString(),
                                writeOffResult.OrderID,
                                writeOffResult.OrderNum,
                                false,
                                false,
                                true,
                            ))
                        }
                    }
                )
            }


        }catch (e: Exception){
            e.printStackTrace()
            log("initYchSdk()异常：${e.message}")
        }
    }

    /**
     * 初始化酷酷宝通讯
     */
    private fun initKkbSdk(param: KkbSdkParam){
        try {
            param.run {
                kkbClient = KkbClient(
                    ssid, mainBoardNum, agreement, agreementVer, devType, title, appSoftVer, netIp, netMask, netGateWay, isTest,
                    object : KkbClient.KkbClientListener{
                        override fun registerFailed(errorCode: Long, errorMsg: String?) {

                        }

                        override fun needUpdate(vararg updateAddress: String?) {

                        }

                        override fun bindStatus(isSuccess: Boolean, deviceNumber: String?) {
                            if (isSuccess) {
                                onLoginSuccess(BackstagePlatform.KKB, deviceNumber)
                            }else{
                                onShowRegist(BackstagePlatform.KKB, true, deviceNumber)
                            }
                        }

                        override fun onError(type: String?, errorCode: Long, msg: String?) {

                        }

                        override fun deviceBinding(devNumber: String) {
                            showToastMsg(context.getString(R.string.binding_and_reboot_tips))
                            val timer = Timer()
                            timer.schedule(object : TimerTask(){
                                override fun run() {
                                    BoardApiUtil.rebootSystem()
                                }
                            }, 3000)
                        }

                        override fun deviceUnBinding() {

                        }

                        override fun deviceReBoot() {
                            BoardApiUtil.rebootSystem()
                        }

                        override fun extractCoin(isMqOrder: Boolean, coins: String, money: String, orderId: String) {
                            if (money == "0"){
                                onReceiveWithdrawalCoinOrder(BackstagePlatform.KKB, RecieveOrderYchBean(
                                    orderId,//事务id
                                    money,
                                    coins,
                                    orderId,//订单id
                                    orderId,//订单号
                                    false,
                                    isMqOrder
                                ))
                            }else{
                                onReceiveOrder(BackstagePlatform.KKB, RecieveOrderYchBean(
                                    orderId,//事务id
                                    money,
                                    coins,
                                    orderId,//订单id
                                    orderId,//订单号
                                    false,
                                    isMqOrder
                                ))
                            }
                        }

                        override fun getDeviceSetting(dataJson: String?) {

                        }

                        override fun setDeviceSetting(dataJson: String?) {

                        }

                        override fun changeCashPackage() {

                        }

                        override fun updateOrder(
                            orderId: String?,
                            transactionId: String?,
                            deviceStatus: Int,
                            remark: String?,
                        ) {

                        }

                        override fun deviceStatues(status: Int) {

                        }

                        override fun loginComplete() {
                            kkbClient?.getCoinPackage(1)//1-普通套餐 2-充值套餐 3-所有套餐
//                            kkbClient?.getConfig()
                        }

                        override fun updateCoinsPackage(coinsPackage: MutableList<KkbGoodBean>) {
                            onRefreshPackageData(BackstagePlatform.KKB, coinsPackage)
                        }

                        override fun updateConfig(configData: KkbGetPayCoinData) {
                            //1元x币配置
                            val defaultCoins = configData.Coins.toString()
                            if (defaultCoins.isNotEmpty()) {
                                val defaultMoneyCoins = Config.DEFAULT_MONEY_COINS.split(",")
                                val dMoney = defaultMoneyCoins[0]
                                val dCoins = defaultMoneyCoins[1]
                                Config.DEFAULT_MONEY_COINS = "100,$dCoins"
                            }

//                            var cashConfig = ""
//                            val banknoteChannelConfigs = CommonUtil.getChannelMode(country).split(";")[0].split(",")
//
//                            banknoteChannelConfigs.forEachIndexed { index, channelCashStr ->
//                                val channelCash = channelCashStr.toLong()
//                                if (channelCash <= 0L){
//                                    cashConfig = "$cashConfig${"0000"}"
//                                    return@forEachIndexed
//                                }
//
//                                configData.CashList.forEach { cash ->
//                                    if (cash.Money*100L == channelCash){
//                                        val coinsHex = ByteUtil.int2HexStr(cash.Coins, 4, true)
//                                        cashConfig = "$cashConfig$coinsHex"
//                                        return@forEachIndexed
//                                    }
//                                }
//                                cashConfig = "$cashConfig${"0000"}"
//                            }
//                            logFile("KKB 纸钞出币配置 $cashConfig")
//                            cashConfigHex = cashConfig
                        }

                        override fun showPayCode(
                            transId: String,
                            orderId: String,
                            orderNumber: String,
                            codeData: String,
                        ) {
                            onShowPayCode(BackstagePlatform.KKB, "$transId,$orderId,$orderNumber,$codeData", 0)
                        }

                        override fun onPlaceOrder(
                            transId: String,
                            orderId: String,
                            orderNumber: String,
                            goodId: String,
                            coins: String,
                            money: String
                        ) {
                            placeOrder(BackstagePlatform.KKB, transId, orderId, orderNumber, goodId, coins, money)
                        }

                        override fun onPlaceCashOrder(
                            transId: String,
                            orderId: String,
                            orderNumber: String,
                            goodId: String,
                            coins: String,
                            money: String
                        ) {
                            placeCashOrderResp(BackstagePlatform.KKB, transId, orderId, orderNumber, goodId, coins, money)
                        }

                        override fun placeOrderResult(transId: String, paySuccess: Boolean) {
                            onReceiveOrderKkbHttp(BackstagePlatform.KKB, RecieveOrderKkbBean(
                                transId,//事务id
                                "",
                                "",
                                transId,//订单id
                                "",//订单号
                                false,
                                false
                            ),
                                paySuccess)
                        }

                        override fun showBuyConsumptionCode(codeData: String) {
                            onShowPayCode(BackstagePlatform.KKB, codeData, 0)
                        }

                        override fun showDevConsumptionCode(codeData: String) {
                            onRecDevConsumeCode(codeData)
                        }

                        override fun getLoginCode(codeData: String, transId: String) {
                            onShowLoginCode("$codeData,$transId")
                        }

                        override fun onLgLogin(loginMemberInfo: KkbQrCodeMemberInfoResponse) {
                            onUserLoginDevKkb(loginMemberInfo)
                        }

                        override fun saveCoinsFinish(balance: Long) {
                            onSaveCoinResult(BackstagePlatform.KKB, true)
                        }

                        override fun consumeCoinsFinish(success: Boolean, errMsg: String?, memberId: String?, balance: Long?) {
                            onConsumeCoinResult(BackstagePlatform.KKB, success, errMsg, memberId, balance)
                        }

                        override fun writeOffResult(writeOffResult: KkbChannelWaitOffData) {
                            onReceiveWriteOffOrder(BackstagePlatform.KKB, RecieveOrderYchBean(
                                writeOffResult.OrderID,
                                "0",
                                writeOffResult.Coin.toString(),
                                writeOffResult.OrderID,
                                writeOffResult.OrderNum,
                                false,
                                false,
                                true,
                            ))
                        }
                    }
                )
            }


        }catch (e: Exception){
            e.printStackTrace()
            log("initYchSdk()异常：${e.message}")
        }
    }

    /**
     * 开启心跳
     */
    private fun startHeartBeat() {
        coroutineScope?.launch(Dispatchers.IO) {
            while (true) {
//                var state = 1
//                val errCode = Constants.COINCONTROL_ERR_CODE
//                if (!Constants.COINCONTROL_HEARTBEAT) {
//                    state = 3
//                }
                val signalStr = BoardApiUtil.getDeviceNetSignal()
                val params = signalStr.split(",")
                val signal = params[1].toInt()
                publishHeartBeat(1, 0, signal)
                delay(30 * 1000L)
            }
        }
    }

    /**
     * mqtt心跳
     * @param state 设备状态
     * @param errCode 故障码
     * @param signal 信号值
     */
    private fun publishHeartBeat(state: Int, errCode: Int, signal: Int) {
//        var state = 1
//        val errCode = Constants.COINCONTROL_ERR_CODE
//        if (!Constants.COINCONTROL_HEARTBEAT) {
//            state = 3
//        }
//        val signal = BoardApiUtil.getInstance().deviceNetSignal
        whmMqtt?.let {
            Logger.d("发送MQTT心跳：设备状态=$state 信号=$signal 故障=$errCode")
            val heartBeatMsg = CmdProducter.heartBeat(state, signal, errCode)
            it.publish(MQConfig.PROTOCOL_VER1, heartBeatMsg!!)
        }
    }

    /**
     * 获取套餐数据，从序号1开始
     *
     * @param packageCount 0-获取套餐数量 >0-套餐数
     * @param packageType 1-充值套餐 2-购币套餐
     */
    private fun publishGetPackage(packageCount: Int, packageType: Int) {
        whmMqtt?.let {
            val pkgMsg: ByteArray
            if (packageCount > 0) {
                pkgMsg = CmdProducter.getPackage(packageCount, packageType)!!
                Logger.d("获取套餐内容数据：" + CmdAssistant.byteArrayToHexStr(pkgMsg))
            } else {
                pkgMsg = CmdProducter.getPackageCount(packageType)!!
                Logger.d("获取套餐数量数据：" + CmdAssistant.byteArrayToHexStr(pkgMsg))
            }
            it.publish(MQConfig.PROTOCOL_VER2, pkgMsg)
        }
    }

    /**
     * 获取lyy盒子二维码
     */
    private fun getLyyBoxQrCode() {
        try {
            lyyBoxQrCodeJob?.cancel()
            lyyBoxQrCodeJob = coroutineScope?.launch(Dispatchers.IO) {
                while (!hasLyyBoxQrCode) {
                    lyyBox?.getQrCode()
                    delay(15000)
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
            logFile("获取lyy盒子二维码异常：${e.message}")
        }
    }

    /**
     * 设备初始化指令，上报iccid
     */
    private fun devInit() {
        coroutineScope?.launch(Dispatchers.IO) {
            var iccidStr = BoardApiUtil.getIccid()
            while (!iccidStr.isNullOrEmpty()) {
                delay(3000)
                iccidStr = BoardApiUtil.getIccid()
            }
            SPHelper.setIccid(iccidStr)
            publishDevInit(iccidStr!!)
        }
    }

    /**
     * mqtt登录指令
     */
    fun publishLogin() {
//        mqttManager?.let {
//            val loginMsg = CmdProducter.loginMessage("1.0.2.4", "4GCY0102", "15978654")
//            Logger.d("上报登录数据：" + CmdAssistant.byteArrayToHexStr(loginMsg))
//            it.publish(MQConfig.PROTOCOL_VER1, loginMsg)
//        }
    }

    /**
     * 设备初始化
     * @param iccid SIM卡iccid
     */
    private fun publishDevInit(iccid: String) {
//        mqttManager?.let {
//            Log.d(TAG, "iccid：$iccid")
//            val loginMsg = CmdProducter.deviceInit("01", iccid, "00", "03", "0.0.0.0", "00")
//            Logger.d("设备初始化数据：" + CmdAssistant.byteArrayToHexStr(loginMsg))
//            Log.d(TAG, "设备初始化数据：" + CmdAssistant.byteArrayToHexStr(loginMsg))
//            it.publish(MQConfig.PROTOCOL_VER1, loginMsg)
//        }
    }


    /**
     * 上报反扫数据
     *
     * @param scanData       反扫数据
     * @param pkgIdOrOutCoin 套餐id或出币数
     * @param payType        支付方式
     * @param business       业务类型
     * @param pkgType        套餐类型
     */
    fun postBackscan(
        bascanPayData: ReqBackscanPayBean
    ) {

        //TODO MQTT

        lyySdk?.let {
            val param = bascanPayData.reqData as BackscanPayParamLyySdk
            logFile("反扫上报数据：${GsonUtil.getInstance()!!.toJson(param)}")
            it.postBackscanPay(
                param.k,
                param.data,
                param.scanData
            )
        }

        lyyBox?.let {
            //TODO
        }

        when (Config.OPEN_MULT_PLATFORM){
            MultPlatform.OPEN -> {}
            MultPlatform.CLOSE -> {
                whmMqttHex?.let {
                    val param = bascanPayData.reqData as BackscanPayParamWhmHex
                    if (param.verificationType == -1) {
                        logFile("反扫上报付款码数据：${GsonUtil.getInstance()!!.toJson(param)}")
//                        it.repReverseData(param.pkgType, param.pkgId, param.payType, param.data)
                        it.repReverseData(param.pkgType, param.pkgId, 2, param.data)
                    } else {
                        logFile("反扫上报核销数据：${GsonUtil.getInstance()!!.toJson(param)}")
                        it.repVerifyData(param.verificationType, param.data)
                    }
                }
            }
        }

        ychClient?.let {
            val param = bascanPayData.reqData as YchBuyPackageBean
            it.placeOrder(param)
        }

        kkbClient?.let {
            val param = bascanPayData.reqData as KkbBuyPackageBean
            it.placeOrder(param)
        }


    }

    /**
     * 获取支付二维码
     * @param payData 支付数据
     */
    fun getPayQrCode(payData: ReqPayCodeBean) {
        //TODO MQTT

        lyySdk?.let {
            val param = payData.reqData as PayCodeParamLyySdk
            it.getPayCode(param.data, param.type.toInt(), param.k)
        }

        lyyBox?.let {
            //TODO
        }

        whmMqtt?.let {
            val param = payData.reqData as PayCodeParamWhmMqtt
            it.getPayCode(param.pkgId, param.payType, param.pkgType)
        }

        when (Config.OPEN_MULT_PLATFORM){
            MultPlatform.OPEN -> {}
            MultPlatform.CLOSE -> {
                whmMqttHex?.let {
                    val param = payData.reqData as PayCodeParamWhmMqttHex
                    it.getPayCode(param.pkgType, param.pkgId, param.payType)
                }
            }
        }

        ychClient?.getConsumptionCode(payData.goodBean.goodId, 0)

        kkbClient?.getConsumptionCode(payData.goodBean.goodId, 0)
    }

    /**
     * 上报出币结果
     * @param resultData 出币信息
     */
    fun reportOutResult(resultData: ReqStartResultBean) {
        //TODO MQTT

        when (resultData.reqData) {
            is StartResultParamLyySdk -> {
                lyySdk?.let {
                    val param = resultData.reqData as StartResultParamLyySdk
                    it.replyStartEq(
                        param.success,
                        param.msg,
                        param.k
                    )
                }
            }

            is StartResultParamLyyBox -> {
                lyyBox?.let {
                    val param = resultData.reqData as StartResultParamLyyBox
                    it.respCloud(param.success)
                }
            }

            is StartResultParamWhmMqttHex -> {
                when (Config.OPEN_MULT_PLATFORM){
                    MultPlatform.OPEN -> {}
                    MultPlatform.CLOSE -> {
                        whmMqttHex?.let {
                            val param = resultData.reqData as StartResultParamWhmMqttHex
                            if (!param.isWithdrawal) {
                                it.repOrderResult(param.k, param.coins, param.success, param.resultReason)
                            }else{
                                it.repDevConsumeResult(param.k, param.needCoins, 3, param.coins, param.success, param.resultReason)
                            }
                        }
                    }
                }
            }

            is StartResultParamYch -> {
                ychClient?.let {
                    val param = resultData.reqData as StartResultParamYch
//                    if (param.isMqOrder){
//                        it.repMqExtractCoinResult(param.resultCode, param.transId)
//
//                        it.repMqExtractCoinResult(param.realCoins.toLong(), param.needCoins.toLong(), param.resultCode, param.remainCoins, param.orderId, param.transId)
//                    }
////                    else if (!param.isMqOrder && param.isWriteOff){
////                        it.repNotMqExtractCoinResult(param.resultCode, param.orderId, "")
////                    }
//                    else{
////                        it.repHttpExtractCoinResult()
//                        logFile("ych上报 ${GsonUtil.getInstance()?.toJson(param)}")
//                        it.repNotMqExtractCoinResult(param.resultCode, param.orderId, "")
//                    }
                    it.repMqExtractCoinResult(param.resultCode, param.transId)

                    it.repMqExtractCoinResult(param.realCoins.toLong(), param.needCoins.toLong(), param.resultCode, param.remainCoins, param.orderId, param.transId)
                }
            }

            is StartResultParamKkb -> {
                kkbClient?.let {
                    val param = resultData.reqData as StartResultParamKkb

                    if (param.isCash) {
                        //现金出币结果上报
                        it.repCashResult(
                            param.totalPriceCent.toLong(),
                            param.realCount.toLong(),
                            param.shouldCount.toLong(),
                            param.result,
//                            param.deviceBalance,
                            -1,
                            param.orderno,
                        )
                    }else if (param.uid.isEmpty()){
                        //反扫出币结果上报
                        it.repMqExtractCoinResult(
                            param.realCount.toLong(),
                            param.shouldCount.toLong(),
                            param.result,
//                            param.deviceBalance,
                            -1,
                            param.orderno,
                            ""
                        )
                    }else{
                        //会员提取数据上报
//                        it.repConsumeCoinsData(param.uid, param.realCount.toLong(), "", param.orderno)
                    }
                }
            }
        }
    }

    fun placeLocalWithdrawalOrder(resultData: ReqStartResultBean){
        when (resultData.reqData) {
            is StartResultParamKkb -> {
                kkbClient?.let {
                    val param = resultData.reqData as StartResultParamKkb
                    //会员提取数据上报
                    it.repConsumeCoinsData(param.uid, param.realCount.toLong(), "", param.orderno)
                }
            }
        }
    }

    fun respTransmissionNumber(snHex: String, dataHex: String){
        whmMqttHex?.repCmdNumberData(snHex, dataHex)
    }

    /**
     * 上报投钞数据
     */
//    fun reportCashData(repCashData: RepCashDataBean) {
//
//        whmMqttHex?.let {
//            val param = repCashData.cashData as RepCashWhmhex
//            val cashDataList: MutableList<CashDataBean> = mutableListOf()
//            param.cashDataList.forEach { item ->
//                cashDataList.add(
//                    CashDataBean(
//                        item.currencyType,
//                        item.currencyUnit,
//                        item.denomination,
//                        item.sum,
//                        item.number,
//                        item.retryCount
//                    )
//                )
//            }
//            it.repCashData(cashDataList)
//        }
//    }

    private fun openBackstage(platform: BackstagePlatform) {
        when (platform) {
            BackstagePlatform.DEF_MQTT -> {

            }

            BackstagePlatform.LYY_SDK -> {
//                initLyyNetty()
            }

            BackstagePlatform.LYY_BOX -> {
//                initLyyBox()
            }

            BackstagePlatform.WHM_MQTT -> {

            }

            BackstagePlatform.WHM_MQTT_HEX -> {

            }

            BackstagePlatform.YCH_SDK -> {

            }

            BackstagePlatform.KKB -> {

            }
        }
    }


    /**
     * 校验lyysdk订单合法性
     * @param k 通讯唯一id
     */
    private fun verifyOrder(k: String): Boolean {

        return true
    }

    /**
     * 获取套餐数据
     */
    private fun lyyGetRule() {
//        lyyClient?.let {
//            LyyClient.getRule()
//        }
    }

    /**
     * 获取支付二维码
     * @param pkgData 套餐内容：套餐id+套餐获得数量+金额（单位分）
     * @param payType 支付类型：0=支付启动，1=会员充值
     * @param k
     */
    private fun lyyGetPayCode(pkgData: String, payType: Int, k: String) {
//        lyyClient?.let {
//            LyyClient.getPayCode(pkgData, payType, k)
//        }
    }

    /**
     * 检查设备
     * @param success 0-正常 1-失败@
     * @param faileMsg
     */
    private fun lyyReplyCheckEq(success: Int, faileMsg: String) {
//        lyyClient?.let {
//            LyyClient.replyCheckEq(success, faileMsg)
//        }
    }

    /**
     * 出币启动状态
     * @param success 0-正常 1-失败
     * @param faileMsg 失败信息
     * @param k 订单id
     */
    private fun lyyReplyStartEq(success: Int, faileMsg: String?, k: String) {
//        lyyClient?.let {
//            LyyClient.replyStartEq(success, faileMsg, k)
//        }
    }

    /**
     * 出币启动结果
     * @param success "1"-成功 “0”-失败
     * @param k 订单号
     * @param failMsg 失败信息
     */
    private fun lyyUploadEqStartResult(success: String, k: String, failMsg: String?) {
//        lyyClient?.let {
//            LyyClient.uploadEqStartResult(success, k, failMsg)
//        }
    }

    /**
     * 上报出币数据
     * @param money 金额
     * @param coins 币数
     */
    fun lyyUploadCommonCoins(money: String, coins: String) {
//        lyyClient?.let {
//            LyyClient.uploadCommonCoins(money, coins)
//        }
    }


    /**
     * 控制板->盒子 上报账目增量
     * @param addCode 自增码
     * @param errCode 故障码
     * @param money 金额
     * @param coins 出币数
     */
    private fun sendCoinListAdd(addCode: String, errCode: String, money: String, coins: String) {
//        lyyBoxController?.uploadCoinListAdd(addCode, errCode, money, coins)
    }

    fun sendGetBoxNetwork() {
//        lyyBoxController?.getBoxNetwork()
    }

    /**
     * 控制板响应链接状态
     * @param loginFlag 登录标识
     */
    fun respConnectState(loginFlag: Int) {
//        when (backstageType){
//            BackstagePlatform.DEFAULT_MQTT -> {
//
//            }
//            BackstagePlatform.LYY_NETTY -> {
//
//            }
//            BackstagePlatform.LYY_BOX -> {
//                lyyBoxController?.respCheckConnect(loginFlag)
//            }
//            BackstagePlatform.YCH_SDK -> TODO()
//        }
    }

    /**
     * 上报出币结果
     * @param baordControlType 控制板类型
     * @param isCashOut 现金购币
     * @param amountStr 金额
     * @param orderNumber 金额
     * @param coins 出币数
     * @param success lyy-sdk 是否出币成功 “0”-成功 “1”-失败
     * @param faileMsg lyy-sdk 失败原因
     */
//    fun postOutCoinsResult(baordControlType: ControlBoardType, isCashOut: Boolean, amountStr: String, orderNumber: String, allCoinsOut: Boolean, coins: Int, success: String, faileMsg: String){
//        when (backstageType) {
//            BackstagePlatform.DEFAULT_MQTT -> {
//
//                if (!isCashOut){
//                    if (!allCoinsOut && coins == 0) {
//                        Logger.d("上报订单状态：出币失败")
//                        publishOrderRespon(0, orderNumber, MQConfig.ORDER_STATE_FAILURE, MQConfig.ORDER_REJECT_ERR)
//                    } else {
//                        Logger.d("上报订单状态：完成")
//                        publishOrderRespon(coins, orderNumber, MQConfig.ORDER_STATE_FINISH, MQConfig.ORDER_REJECT_DEFAULT)
//                    }
//                }
//            }
//
//            BackstagePlatform.LYY_NETTY -> {
//                val k = orderNumber
//                lyyUploadEqStartResult(success, k, faileMsg)
//                DBManager.deleteLyySelectPackage(k).subscribe()
//            }
//
//            BackstagePlatform.LYY_BOX -> {
//                if (baordControlType == ControlBoardType.BOARD_LYY){
//                    log("lyy控制板，不需要插手上报出币结果，控制板会自动上报0x14指令")
//                    return
//                }
//                sendCoinListAdd("-1", "0",
//                    amountStr, coins.toString())
//            }
//
//            BackstagePlatform.YCH_SDK -> {
//
//            }
//        }
//    }

    /**
     * 现金下单
     */
    fun placeCashOrder(repData: Any){
        kkbClient?.let {
            val param = repData as KkbBuyPackageBean
            it.placeCashOrder(param)
        }
    }

    /**
     * 上报账目增量（上报纸钞数据）
     * @param addCode 自增码
     * @param errCode 故障码
     * @param money 金额
     * @param coins 出币数
     */
    fun uploadCoinListAdd(repData: Any) {
        //TODO MQTT

        lyySdk?.let {
            val param = repData as RepCashLyysdk
            it.uploadCommonCoins(param.money, param.coins)
        }

        lyyBox?.let {
            //TODO
        }

        when (Config.OPEN_MULT_PLATFORM){
            MultPlatform.OPEN -> {}
            MultPlatform.CLOSE -> {
                whmMqttHex?.let {
                    val param = repData as RepCashWhmhex
                    val cashDataList: MutableList<CashDataBean> = mutableListOf()
                    param.cashDataList.forEach { item ->
                        cashDataList.add(
                            CashDataBean(
                                item.currencyType,
                                item.currencyUnit,
                                item.denomination,
                                item.sum,
                                item.number,
                                item.retryCount
                            )
                        )
                    }
                    it.repCashData(cashDataList)
                }
            }
        }

        ychClient?.let {
            val param = repData as RepCashYch
            it.repCashData(com.sy.simpleegg.platform.ychsdk.bean.pay.RepCashDataBean(
                param.transId,
                param.count.toString(),
                param.money,
                param.machineBalance,
                param.outStatus,
                param.expected,
                param.serialPortInfo,
                param.creatTime,
                param.vending,
                param.msg,

            ))
        }

        kkbClient?.let {
            val param = repData as RepCashKkb
            it.repCashData(
                RepCashDataBean(
                param.transId,
                param.count.toString(),
                param.money,
                param.machineBalance,
                param.outStatus,
                param.expected,
                param.serialPortInfo,
                param.creatTime,
                param.vending,
                param.msg,
            )
            )
        }
    }

    /**
     * 上报存币数据
     * @param repData 上报数据
     */
    fun uploadSaveCoinData(repData: RepCoinDataBean) {
        //TODO MQTT

//        whmMqttHex?.let {
//            val param = repData.repData as RepCoinWhmhex
//            val coinDataList: MutableList<CoinsDataBean> = mutableListOf()
//            param.coinDataList.forEach { item ->
//                coinDataList.add(
//                    CoinsDataBean(
//                        item.type,
//                        item.unit,
//                        item.sum
//                    )
//                )
//            }
//            it.repSaveCoinsData(param.userId, coinDataList)
//        }

        whmUserInfo?.let { user ->

            when (Config.OPEN_MULT_PLATFORM){
                MultPlatform.OPEN -> {}
                MultPlatform.CLOSE -> {
                    whmMqttHex?.let {

                        val param = repData.repData as RepCoinWhmhex
                        val coinDataList: MutableList<CoinsDataBean> = mutableListOf()
                        var saveAmount = 0L
                        param.coinDataList.forEach { item ->
                            coinDataList.add(
                                CoinsDataBean(
                                    item.type,
                                    item.unit,
                                    item.sum
                                )
                            )
                            saveAmount += item.sum
                        }

                        val userTotalAmount = user.accountCoins.toLong() + user.giftCoins.toLong()
                        val balance = userTotalAmount + saveAmount
                        it.repDevSaveWallet(
                            user.loginToken,
                            user.userId,
                            saveAmount,
                            4,
                            saveAmount,
                            balance,
                            1,
                            1
                        )
                    }
                }
            }
        }

        ychClient?.let {
            val param = repData.repData as RepCoinYch
            it.repSaveCoinsData(param.leaguerId, param.num, param.remark, param.transId)
        }

        kkbClient?.let {
            val param = repData.repData as RepCoinKkb
            it.repSaveCoinsData(param.leaguerId, param.num, param.remark, param.transId)
        }
    }

    /**
     * 取消 查询下单支付结果
     */
    fun queryPlaceOrderCancel(transId: String){
        ychClient?.removeQueryOrder(transId)

        kkbClient?.removeQueryOrder(transId)
    }

    /**
     * 取消 查询会员扫码登录
     */
    fun queryLgLoginCancel(){
        ychClient?.removeQueryLgLogin()

        kkbClient?.removeQueryLgLogin()
    }

    /**
     * 取消 查询会员扫码登录
     */
    fun logout(){
        when (Config.OPEN_MULT_PLATFORM){
            MultPlatform.OPEN -> {}
            MultPlatform.CLOSE -> {
                whmMqttHex?.repLogout("", 0)
            }
        }
    }

    /**
     * 解析透传数据
     * @param dataHex
     */
    private fun parseTransmissionData(snHex: String, dataHex: String) {
        try {
            val flag = dataHex.substring(0, 2).toInt(16)
            when (flag) {
                1 -> {
                    getBasicConfigToResp(snHex)
                }
                2 -> {
                    //设备参数
                    val motorModeHex = dataHex.substring(2, 4)
                    val motor1StateHex = dataHex.substring(4, 6)
                    val motor2StateHex = dataHex.substring(6, 8)
                    val dispenser1StateHex = dataHex.substring(8, 10)
                    val dispenser1ProportionHex = "${dataHex.substring(12, 14)}${dataHex.substring(10, 12)}"
                    val dispenser2StateHex = dataHex.substring(14, 16)
                    val dispenser2ProportionHex = "${dataHex.substring(18, 20)}${dataHex.substring(16, 18)}"
                    val banknote1Hex = dataHex.substring(20, 22)
                    val banknote2Hex = dataHex.substring(22, 24)
                    val cashProportionHex = "${dataHex.substring(26, 28)}${dataHex.substring(24, 26)}"
                    val verHex = dataHex.substring(28, 44)
                    val cashCountryHex = dataHex.substring(44, 46)

                    val deviceConfig = DeviceConfig(
                        dataHex.substring(2, 4).toInt(16),//马达模式
                        dataHex.substring(4, 6).toInt(16),//马达1状态
                        dataHex.substring(6, 8).toInt(16),//马达2状态
                        dataHex.substring(8, 10).toInt(16),//投币器1开关
                        dataHex.substring(10, 14).toInt(16),//投币器1出币比例
                        dataHex.substring(14, 16).toInt(16),//投币器2开关
                        dataHex.substring(16, 20).toInt(16),//投币器2现金比例
                        dataHex.substring(20, 22).toInt(16),//纸钞机1开关
                        dataHex.substring(22, 24).toInt(16),//纸钞机2开关
                        dataHex.substring(24, 28).toInt(16),//现金出币比例
                        HexUtil.hexStrToStr(
                            HexUtil.splitZeroLeft(
                                dataHex.substring(
                                    28,
                                    44
                                )
                            )
                        )!!,//软件版本号
                        dataHex.substring(44, 46).toInt(16)//国家
                    )
                    val configHex = "$motorModeHex$motor1StateHex$motor2StateHex$dispenser1StateHex$dispenser1ProportionHex$dispenser2StateHex$dispenser2ProportionHex$banknote1Hex$banknote2Hex$cashProportionHex$cashCountryHex"
                    onRecBasicConfig(configHex)
                    if (deviceConfig.country != country) {
                        country = deviceConfig.country
                        Config.CURRENCY_SYMBOLS =
                            CommonUtil.getCurrencySymbols(deviceConfig.country)
                        if (switchLanguage(CommonUtil.getLanguage(deviceConfig.country))) {
                            onRestartApp()
                        }
                    }
                }
                3 -> {
                    getCashConfigToResp(snHex)
                }
                4 -> {
                    //现金套餐
                    val cashConfig = CashConfigBean(
                        dataHex.substring(2, 4) == "01",//通道一状态
                        dataHex.substring(4, 10).toLong(16),//通道一出币数

                        dataHex.substring(10, 12) == "01",//通道二状态
                        dataHex.substring(12, 18).toLong(16),//通道二出币数

                        dataHex.substring(18, 20) == "01",//通道三状态
                        dataHex.substring(20, 26).toLong(16),//通道三出币数

                        dataHex.substring(26, 28) == "01",//通道四状态
                        dataHex.substring(28, 34).toLong(16),//通道四出币数

                        dataHex.substring(34, 36) == "01",//通道五状态
                        dataHex.substring(36, 42).toLong(16),//通道五出币数

                        dataHex.substring(2, 4) == "01",//通道六状态
                        dataHex.substring(42, 44).toLong(16),//通道六出币数

                        dataHex.substring(44, 46) == "01",//通道七状态
                        dataHex.substring(46, 52).toLong(16),//通道七出币数

                        dataHex.substring(52, 54) == "01",//通道八状态
                        dataHex.substring(54, 60).toLong(16),//通道八出币数

                        dataHex.substring(60, 62) == "01",//通道九状态
                        dataHex.substring(62, 68).toLong(16),//通道九出币数

                        dataHex.substring(68, 70) == "01",//通道十状态
                        dataHex.substring(70, 76).toLong(16),//通道十出币数
                    )
                    onRecCashConfig(cashConfig)
                }

                5 -> {
                    //马达参数
                    getMotorConfigToResp(snHex)
                }

                6 -> {
                    //设置马达参数
                    val motorConfigBean = MotorConfigBean(dataHex.substring(0, 2).toInt(16), dataHex.substring(2, 4).toInt(16), dataHex.substring(4, 6).toInt(16))
                    onRecMotorConfig(motorConfigBean)
                }

                else -> logFile("未定义指令：$dataHex")
            }
        } catch (e: Exception) {
            e.printStackTrace()

        }
    }

    private fun switchLanguage(languageParam: String): Boolean {
        if (languageParam.isEmpty()) return false
        val lan = languageParam.split(",")[0]
        val area = languageParam.split(",")[1]
        Languages.entries.forEach { lanItem ->
            if (lanItem.lan == lan && lanItem.area == area) {
                language = lanItem
                return MultiLanguageUtils.changeLanguage(context, lan, "r$area")
            }
        }
        return false
    }

    /**
     * 获取消费者登录二维码
     */
    fun getLoginCode(){
        when (Config.OPEN_MULT_PLATFORM){
            MultPlatform.OPEN -> {}
            MultPlatform.CLOSE -> {
                whmMqttHex?.getLoginCode()
            }
        }
        ychClient?.getLoginCode()
        kkbClient?.getLoginCode()
    }

    /**
     * 获取提币二维码
     */
    fun getWithdrawalCode(){
        when (Config.OPEN_MULT_PLATFORM){
            MultPlatform.OPEN -> {}
            MultPlatform.CLOSE -> {
                whmMqttHex?.getWithdrawalCode(1)
            }
        }

        ychClient?.getConsumptionCode("", 1)

        kkbClient?.getConsumptionCode("", 1)
    }

    /**
     * 上报核销数据
     */
    fun repWriteOffData(repData: Any){
        when (Config.OPEN_MULT_PLATFORM){
            MultPlatform.OPEN -> {}
            MultPlatform.CLOSE -> {
                whmMqttHex?.let {
                    val param = repData as RepWriteOffWhm
                    it.repVerifyData(param.channel.toInt(), param.codeData)
                }
            }
        }

        ychClient?.let {
            val param = repData as RepWriteOffYch
            it.repWriteOffData(param.codeData, param.channel, param.amount)
        }

        kkbClient?.let {
            val param = repData as RepWriteOffKkb
            it.repWriteOffData(param.codeData, param.channel, param.amount)
        }
    }

    /**
     * 刷新注册码
     */
    private fun refreshRegCode(platform: BackstagePlatform, code: String, status: Int){
        regCodeMap[platform.backstageName]?.apply {
            this.code = code
            this.status = status
        }?.let {
            val regDataList: MutableList<RegDataBean> = mutableListOf()
            regCodeMap.entries.forEach { map ->
                //注册完成，不需要加入注册设备列表
                if (map.value.status == 2) return@forEach
                regDataList.add(map.value)
            }
            onPostRegData(regDataList)
        }
    }

    private fun setWifi(ssid: String, pwd: String){
        coroutineScope?.launch {
            val wifiName = ssid
            val wifiPassword = pwd
            if (wifiName.isEmpty()){
                WifiUtil.mInstance.closeWifi()
                return@launch
            }

            coroutineScope?.launch {
                if (!WifiUtil.mInstance.isWifiEnable()){
                    WifiUtil.mInstance.openWifi()
                    delay(3000)
                }

                val canScan = WifiUtil.mInstance.startScanWifi()

                if (canScan == null){
                    return@launch
                }else{
                    if (canScan){
                        delay(3000)
                    }else{
                        return@launch
                    }
                }

                var connectState = false
                WifiUtil.mInstance.setWifiConnectCallback(object : WifiUtil.ConnectedCallback{
                    override fun connectSuccessed() {
                        connectState = true
                        Log.d(javaClass.simpleName, "wifi连接成功")
                    }

                    override fun connectFailed() {
                        connectState = false
                        Log.d(javaClass.simpleName, "wifi连接失败")
                    }
                })

                WifiUtil.mInstance.connectWifi(wifiName, wifiPassword)

                var connectCompleted = false
                var checkCount = 0
                while (!connectCompleted && checkCount < 20){
                    delay(1000)
                    checkCount ++
                    connectCompleted = WifiUtil.mInstance.connectCompleteed()
                    Log.d(javaClass.simpleName, "连接的wifi状态：$connectCompleted")
                }
            }
        }
    }

    /**
     * mqtt执行登录指令
     */
    abstract fun toLogin()

    /**
     * 登录成功
     * @param platform 登录平台
     * @param devNumber 设备号
     */
    abstract fun onLoginSuccess(platform: BackstagePlatform, devNumber: String?)

    /**
     * 链接状态改变
     * @param platform 平台
     * @param connectState 链接专题
     */
    abstract fun onConnectionChange(platform: BackstagePlatform, connectState: Boolean)

    /**
     * 套餐数据
     * @param platform 平台
     * @param pkgCount 套餐数量
     * @param pkgType 套餐类型
     */
    abstract fun onGetPackage(platform: BackstagePlatform, pkgCount: Int, pkgType: Int)

    /**
     * 刷新套餐数据
     * @param platform 平台
     * @param dataList 套餐数据
     */
    abstract fun onRefreshPackageData(platform: BackstagePlatform, dataList: Any)

    /**
     * 投钞数据响应
     * @param platform 平台
     * @param sucess 平台
     * @param billMsgNumber 消息编号
     */
    abstract fun onBillResp(platform: BackstagePlatform, sucess: Boolean, billMsgNumber: String)

    /**
     * 收到订单
     * @param platform 平台
     * @param orderEntity 订单数据
     * @param msg
     */
//        fun onReceiveOrder(platform: BackstagePlatform, orderEntity: OrderEntity, msg: String?)

    /**
     * 显示二维码或者图片
     * @param platform 平台
     * @param codeData 显示数据
     * @param showType 显示类型 0-二维码 1-图片
     */
    abstract fun onShowPayCode(platform: BackstagePlatform, codeData: String?, showType: Int)

    /**
     * 存币结果上报
     * @param platform 平台
     * @param result true-上报成功 false-上报失败
     */
    abstract fun onSaveCoinResult(platform: BackstagePlatform, result: Boolean)

    /**
     * 取币结果
     * @param platform 平台
     * @param result true-上报成功 false-上报失败
     */
    abstract fun onConsumeCoinResult(platform: BackstagePlatform, success: Boolean, errMsg: String?, memberId: String?, balance: Long?)

    /**
     * 支付成功
     * @param platform 平台
     * @param k 订单号
     */
    abstract fun onReceiveOrder(platform: BackstagePlatform, orderData: Any)

    /**
     * 油菜花查询订单支付成功
     * @param platform 平台
     * @param paySuccessed 支付状态
     */
    abstract fun onReceiveOrderYchHttp(platform: BackstagePlatform, orderDataYch: RecieveOrderYchBean, paySuccessed: Boolean)

    /**
     * 酷酷宝查询订单支付成功
     * @param platform 平台
     * @param paySuccessed 支付状态
     */
    abstract fun onReceiveOrderKkbHttp(platform: BackstagePlatform, orderDataKkb: RecieveOrderKkbBean, paySuccessed: Boolean)

    /**
     * 收到提币订单
     * @param platform 平台
     * @param orderData 订单数据
     */
    abstract fun onReceiveWithdrawalCoinOrder(platform: BackstagePlatform, orderData: Any)

    /**
     * 收到核销订单
     * @param platform 平台
     * @param orderData 订单数据
     */
    abstract fun onReceiveWriteOffOrder(platform: BackstagePlatform, orderData: Any)

    /**
     * 显示提示信息
     * @param platform 平台
     * @param colorType 文本颜色类型 1-黑色 其他-红色
     * @param tips 显示内容
     */
    abstract fun onShowTips(platform: BackstagePlatform, colorType: Int, tips: String)

    /**
     * 显示注册码
     * @param platform 平台
     * @param isShow 0-显示 1-隐藏
     * @param registCode 注册二维码
     */
    abstract fun onShowRegist(platform: BackstagePlatform, isShow: Boolean, registCode: String?)

    /**
     * lyy盒子出币结果控制板
     */
    abstract fun lyyRespLyyBoardOutResult(platform: BackstagePlatform, dataHex: String)
    /**
     * lyy盒子下发支付二维码连接
     * @param codeDataHex 二维码内容
     */
//        fun lyyToShowPayQrCode(codeDataHex: String)
    /**
     * lyy盒子回复lyy控制板账目增量
     */
    abstract fun lyyRespListAdd(platform: BackstagePlatform, dataHex: String)

    /**
     * lyy盒子回复lyy控制板网络状态
     */
    abstract fun lyyRespBoxNetwork(platform: BackstagePlatform, dataHex: String)

    /**
     * lyy盒子控制板网络状态
     * @param dataHex 盒子下发的完整16进制数据，如果控制板是lyy的，可以直接转发
     * @param uniqueCodeHex 唯一码 非lyy控制板使用
     */
    abstract fun lyyCheckBoardConnecton(
        platform: BackstagePlatform,
        dataHex: String,
        uniqueCodeHex: String
    )

    /**
     * lyy盒子查询控制板运行状态
     * @param dataHex 盒子下发的完整16进制数据，如果控制板是lyy的，可以直接转发
     * @param uniqueCodeHex 唯一码 非lyy控制板使用
     */
    abstract fun lyyGetBoardState(
        platform: BackstagePlatform,
        dataHex: String,
        uniqueCodeHex: String
    )

    /**
     * lyy盒子获取控制板参数
     */
    abstract fun lyyGetBoardConfig(platform: BackstagePlatform, dataHex: String)

    /**
     * lyy盒子设置控制板参数
     */
    abstract fun lyySetBoardConfig(platform: BackstagePlatform, dataHex: String)

    /**
     * lyy盒子心跳
     */
    abstract fun lyyRespBoxHeartBeat(platform: BackstagePlatform, heartBeat: Boolean)

    abstract fun onRestartApp()

    abstract fun onRecCashConfig(cashConfigBean: CashConfigBean)

    abstract fun onRecMotorConfig(motorConfigBean: MotorConfigBean)

    abstract fun getBasicConfigToResp(snHex: String)

    abstract fun getCashConfigToResp(snHex: String)

    abstract fun getMotorConfigToResp(snHex: String)

    abstract fun onRecBasicConfig(basicConfigHex: String)

    abstract fun onUserLoginDev(recUserInfoNew: RecUserInfoNew)

    abstract fun onUserLoginDevYch(loginMemberInfo: QrCodeMemberInfoResponse)

    abstract fun onUserLoginDevKkb(loginMemberInfo: KkbQrCodeMemberInfoResponse)

    abstract fun onShowLoginCode(code: String)

    abstract fun onShowWithdrawalCode(code: String)

    abstract fun onRecDevConsumeCode(code: String)

    abstract fun onDevLogoutResp()

    abstract fun placeOrder(platform: BackstagePlatform, transId: String, orderId: String, orderNumber: String, goodId: String, coins: String, money: String)

    abstract fun placeCashOrderResp(platform: BackstagePlatform, transId: String, orderId: String, orderNumber: String, goodId: String, coins: String, money: String)

    abstract fun onPostRegData(regDataList: MutableList<RegDataBean>)

    abstract fun onWriteOffResult(platform: BackstagePlatform, writeOffResp: Any)

    abstract fun onUpgrade(fileId: String, name: String, url: String)

    abstract fun onUploadLog(logType: Int, logNumber: String)

    private fun log(msg: String) {
        logFile(msg)
    }
}